package com.firexxx.study;

import java.util.HashMap;
import java.util.Map;

/**
 * @description: TODO
 * @throws:
 * @author: zhuangzhang2
 * @date: 2020/07/05 01:17
 */
public class TimeCache {
    public static Map<String, Map<String, Long>> startTimeThreadMap = new HashMap<>();
    public static Map<String, Map<String, Long>> endTimeThreadMap = new HashMap<>();

    public static void setThreadName(String threadName) {
        if (startTimeThreadMap.containsKey(threadName)) {
            startTimeThreadMap.get(threadName).clear();
        } else {
            startTimeThreadMap.put(threadName, new HashMap<>());
        }

        if (endTimeThreadMap.containsKey(threadName)) {
            endTimeThreadMap.get(threadName).clear();
        } else {
            endTimeThreadMap.put(threadName, new HashMap<>());
        }
    }

    public static void setStartTime(String threadName, String methodName, long time) {
        startTimeThreadMap.get(threadName).put(methodName, time);
    }

    public static void setEndTime(String threadName, String methodName, long time) {
        endTimeThreadMap.get(threadName).put(methodName, time);
    }

    public static String getCostTime(String threadName, String prefix, String methodName) {
        if(methodName == null){
            return "";
        }

//        System.out.println("方法名为" + methodName);
        Map<String, Long> startTimeMap = startTimeThreadMap.get(threadName);
        Map<String, Long> endTimeMap = endTimeThreadMap.get(threadName);

        if (!startTimeMap.containsKey(methodName) || !endTimeMap.containsKey(methodName)) {
            return "exception:" + methodName;
        }

        long start = startTimeMap.get(methodName);
        long end = endTimeMap.get(methodName);
        return prefix + threadName + "-" + methodName + " cost:[" + (end - start) + " ms]";
    }

    public static void clear(String threadName) {
        if (startTimeThreadMap.containsKey(threadName)) {
            startTimeThreadMap.get(threadName).clear();
        }

        if (endTimeThreadMap.containsKey(threadName)) {
            endTimeThreadMap.get(threadName).clear();
        }
    }
}